package com.ynjt.util;

import com.ynjt.model.Message;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;

import java.util.List;

public class Decoder extends ByteToMessageDecoder {

    @Override
    protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf in, List<Object> out) throws Exception {

        if(in.readableBytes() < (Integer.SIZE / Byte.SIZE) * 4){
            return;
        }

        in.markReaderIndex();
        int idLength = in.readInt();
        int nameLength = in.readInt();
        int ipLength = in.readInt();
        int contentLength = in.readInt();

        if(in.readableBytes() < (idLength + nameLength + ipLength + contentLength)){
            in.resetReaderIndex();
            return;
        }

        byte[] idByte = new byte[idLength];
        in.readBytes(idByte);
        final String idStr = new String(idByte, "utf-8");

        byte[] nameByte = new byte[nameLength];
        in.readBytes(nameByte);
        String nameStr = new String(nameByte, "utf-8");

        byte[] ipByte = new byte[ipLength];
        in.readBytes(ipByte);
        String ipStr = new String(ipByte, "utf-8");


        byte[] contentByte = new byte[contentLength];
        in.readBytes(contentByte);
        String contentStr = new String(contentByte, "utf-8");
        Message message = new Message(idStr,nameStr,ipStr,contentStr);
        out.add(message);

    }
}
